package com.bolovan.infovaluta.reader;

import java.io.IOException;
import java.math.BigDecimal;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.bolovan.infovaluta.bean.ExchangeRate;
import com.bolovan.infovaluta.bean.ExchangeRateEntry;
import com.bolovan.infovaluta.bean.ExchangeRateSeller;
import com.bolovan.infovaluta.util.RateConstants;
import com.bolovan.infovaluta.util.RateMaps;
import com.bolovan.infovaluta.util.RateUtil;

public class BceReader extends ExchangeReader {

	public BceReader(ExchangeRateSeller seller) {
		super(seller);
	}

	@Override
	public void buildRateMap(ExchangeRate map) throws IOException {
		fetchBCE(map);
	}

	private void fetchBCE(ExchangeRate map) throws IOException {

		Document doc = RateUtil.getDocument(ExchangeRateSeller.BCE.getUrl());
		setDate(doc.select("cube[time]").last().attr("time"));
		setParsingDate(RateMaps.date);

		Elements rates = doc.select("cube[rate]");
		for (Element e : rates) {
			String currency = e.attr("currency");
			Integer multiplier = 1;
			if (RateConstants.multiplierCurrencyes.contains(currency)) {
				multiplier = 100;
			}
			Double val = multiplier / Double.valueOf(e.attr("rate"));

			map.addToMap(new ExchangeRateEntry(currency, new BigDecimal(val), null, multiplier));
		}

	}
}
